package com.hthy.futures.ui.fragment;


import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hthy.futures.AppConfig;
import com.hthy.futures.AppContext;
import com.hthy.futures.R;
import com.hthy.futures.api.ST_TradeApi;
import com.hthy.futures.base.BaseFragment;
import com.hthy.futures.bean.Goods;
import com.hthy.futures.bean.OrderTicket;
import com.hthy.futures.bean.SaveQuotePush;
import com.hthy.futures.bean.ht.BRealTimeData;
import com.hthy.futures.bean.ht.BRealTimeQuotePush;
import com.hthy.futures.bean.ht.ChooseGood;
import com.hthy.futures.utils.CacheManager;
import com.hthy.futures.utils.DialogUtil;
import com.hthy.futures.utils.ErrorUtils;
import com.hthy.futures.utils.LogUtils;
import com.hthy.futures.utils.StringUtils;
import com.vilyever.socketclient.SocketClient;

import net.hthy.bean.Trade;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * 资金   (他要和行情推送相结合，计算出对应的值）
 * Author:  Mr.bingley
 * Version:
 * Date:  2017/3/6
 */


/**
 * 单据、商品、个人信息
 * <p>
 * 第一步先请求 查询所有商品，把商品的价格替换为行情中的价格，然后
 * 买方向单据浮动盈亏
 * =（（行情价+报价卖点差）- 持仓价格）* 合约单位 * 成交数量
 * 卖方向单据浮动盈亏
 * =（持仓价格 -（行情价+报价买点差））* 合约单位 * 成交数量
 * 客户总浮动盈亏 = 买方向单据浮动盈亏 + 卖方向单据浮动盈亏
 * <p>
 * <p>
 * --1 查询去单据中拿到中判断买、卖方向。
 */

public class FundFragment extends BaseFragment {
    @Bind(R.id.tv_float_profit)
    TextView mTvFloatProfit;
    @Bind(R.id.tv_open_profit)
    TextView mTvOpenProfit;
    @Bind(R.id.tv_take_margin)
    TextView mTvTakeMargin;
    @Bind(R.id.tv_close_margin)
    TextView mTvCloseMargin;
    @Bind(R.id.tv_available_margin)
    TextView mTvAvailableMargin;
    @Bind(R.id.tv_previous_balance)
    TextView mTvPreviousBalance;
    @Bind(R.id.tv_risk_rate)
    TextView mTvRiskRate;
    @Bind(R.id.tv_risk_level)
    TextView mTvRiskLevel;
    @Bind(R.id.ll_fund)
    LinearLayout mLlFund;
    @Bind(R.id.tv_net_worth)
    TextView mTvNetWorth;
    @Bind(R.id.tv_account)
    TextView mTvAccount;
    @Bind(R.id.tv_userName)
    TextView mTvUserName;


    // 筛选后的持仓单数据
    List<OrderTicket> mOrderTickets = new ArrayList<>();

    List<Goods> mGoodsList = new ArrayList<>();
    List<ChooseGood> mChooseGoods = new ArrayList<>();
    private boolean isFromFund;
    private boolean isFromFund2;
    private boolean isFromFundRequest;
    private double mFreezeMargin;
    private double net_worth;
    private double mAdditionalMarginRisk;
    private double mAutomaticRiskliquidation;
    private List<BRealTimeQuotePush> mBrealTimeQuotePushes;
    private double mDbFreeMargin;

    @Override
    protected int getLayoutId() {
        return R.layout.frg_fund;
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        mLlFund.setVisibility(View.GONE);
        DialogUtil.showDialog(getActivity());
        // 初始化用戶名和账号
        mTvUserName.setText("用户：" + AppContext.accountName);
        mTvAccount.setText("账号：" + AppContext.account);
    }

    @Override
    protected void initData() {
        byte[] baseStr2 = ST_TradeApi.searchGoods("2003");   // c查询资金
        socketClient.sendData(baseStr2);
        isFromFundRequest = true;

    }

    public void refrsh() {
        //showVisiable();
        isFromFund = false;
        isFromFund2 = false;
        initData();
    }

    @Override
    protected void onResponse(SocketClient client, String responMes, byte[] subBytes) {
        super.onResponse(client, responMes, subBytes);
        LogUtils.e(responMes);

        // 之所以要判断是否是某个命令，防止多次回调onresponse方法造成的误差
        if (isFromFundRequest && responMes.indexOf("2004") != -1) {
            // 然后接着从返回的数据中截掉前面的37位，剩下就是json字符串内容。
            try {

                Trade.QueryUserFundResponseMsg queryUserFundResponseMsg = Trade.QueryUserFundResponseMsg.parseFrom(subBytes);
                Trade.UserFundDetail userFundDetail = queryUserFundResponseMsg.getUserFundDetail();

                double dbClosePl = userFundDetail.getDbClosePl();
                mTvOpenProfit.setText(StringUtils.double_df.format(dbClosePl));  // 这个是平仓盈亏
                if (dbClosePl > 0) {
                    mTvOpenProfit.setTextColor(getResources().getColor(R.color.red));
                } else {
                    mTvOpenProfit.setTextColor(getResources().getColor(R.color.fund_float));
                }

                mFreezeMargin = userFundDetail.getDbReservedMargin();
                mTvCloseMargin.setText(StringUtils.double_df.format(mFreezeMargin));       // 冻结保证金

                mDbFreeMargin = userFundDetail.getDbFreeMargin();
                //  double availMoney = StringUtils.toDouble(mFund.getValue8035());
                //  mTvAvailableMargin.setText(StringUtils.double_df.format(availMoney));  // 可用保证金

                mTvNetWorth.setText("0");
                mTvPreviousBalance.setText(StringUtils.double_df.format(userFundDetail.getDbInitEquity()));      //上日结余

                mAdditionalMarginRisk = queryUserFundResponseMsg.getDbMarginCallRate();
                mAutomaticRiskliquidation = queryUserFundResponseMsg.getDbStopOutRate();


                isFromFundRequest = false;

                showVisiable();
                // 先获取商品种类
                byte[] baseStr2 = ST_TradeApi.searchGoods("2015");
                socketClient.sendData(baseStr2);
                isFromFund2 = true;
            } catch (Exception e) {
                e.printStackTrace();
            }

        }


        //从查询交易商品获取
        if (isFromFund2 && responMes.indexOf("2016") != -1) {
            try {

                if (mGoodsList != null && mGoodsList.size() > 0) {
                    mGoodsList.clear();
                }
                Trade.QueryProductsResponseMsg queryProductsResponseMsg = Trade.QueryProductsResponseMsg.parseFrom(subBytes);
                List<Trade.UserProductsInfo> userProductsInfoList = queryProductsResponseMsg.getUserProductsInfoList();
                for (Trade.UserProductsInfo productsInfo : userProductsInfoList) {
                    Goods goods = new Goods();
                    goods.setSs_product_code(productsInfo.getSsProductCode());
                    goods.setSs_product_name(productsInfo.getSsProductName());
                    goods.setUi_buy_pips(productsInfo.getUiBuyPips() + "");
                    goods.setUi_sell_pips(productsInfo.getUiSellPips() + "");
                    goods.setUi_sl_pips(productsInfo.getUiSlPips() + "");
                    goods.setUi_tp_pips(productsInfo.getUiTpPips()+"");
                    goods.setDb_contract_size(productsInfo.getDbContractSize()+"");
                    goods.setDb_origin_margin(productsInfo.getDbOriginMargin() + "");
                    goods.setUi_margin_type(productsInfo.getUiMarginType() == 49? "1" : "2");
                    mGoodsList.add(goods);
                }
                if (mChooseGoods.size() > 0) {
                    mChooseGoods.clear();
                }
                for (Goods goods : mGoodsList) {
                    ChooseGood chooseGood = new ChooseGood();
                    chooseGood.goodsCode = goods.getSs_product_code();
                    chooseGood.goodsName = goods.getSs_product_name();
                    chooseGood.buyPriceSpreed = goods.getUi_buy_pips();
                    chooseGood.sellPriceSpreed = goods.getUi_sell_pips();
                    chooseGood.contractUnit = goods.getDb_contract_size();
                    chooseGood.moneyHoldType = goods.getUi_margin_type();
                    chooseGood.initGuaranteeMoney = goods.getDb_origin_margin();
                    mChooseGoods.add(chooseGood);
                }

                byte[] baseStr2 = ST_TradeApi.searchGoods("2005");  // ordeericket
                socketClient.sendData(baseStr2);
                isFromFund = true;
                isFromFund2 = false;
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        // 查询单据应答
        if (isFromFund && responMes.indexOf("2006") != -1) {
            try {
                Trade.QueryOrderResponseMsg queryOrderResponseMsg = Trade.QueryOrderResponseMsg.parseFrom(subBytes);
                if (queryOrderResponseMsg != null) {
                    int iErrorCode = queryOrderResponseMsg.getResponseMsg().getIErrorCode();
                    if (0 == iErrorCode) {
                        List<Trade.UserOrderDetail> userOrderDetails = queryOrderResponseMsg.getOrderDetailList();   // 单据list
                        if (userOrderDetails != null && userOrderDetails.size() > 0) {
                            List<OrderTicket> mDatas = new ArrayList<>();
                            for (Trade.UserOrderDetail userOrderDetail : userOrderDetails) {
                                OrderTicket orderTicket = new OrderTicket();
                                orderTicket.setDbExecuteSize(userOrderDetail.getDbExecuteSize() + "");
                                orderTicket.setDbOrderSize(userOrderDetail.getDbOrderSize() + "");
                                orderTicket.setOrderStatusValue(userOrderDetail.getOrderStatusValue() + "");   // 这个是单据的状态,是个枚举类型的
                                orderTicket.setOrderDirectionValue(userOrderDetail.getOrderDirectionValue()==1?"b":"s");  //
                                orderTicket.setSsProductCode(userOrderDetail.getSsProductCode() + "");
                                orderTicket.setDbTpPrice(userOrderDetail.getDbTpPrice() + "");
                                orderTicket.setDbSlPrice(userOrderDetail.getDbSlPrice() + "");
                                orderTicket.setLimitOrderType(userOrderDetail.getLimitOrderTypeValue() + "");  //
                                orderTicket.setDbHoldPrice(userOrderDetail.getDbHoldPrice() + "");
                                orderTicket.setSsExecuteTime(userOrderDetail.getSsExecuteTime());
                                orderTicket.setUiOrderCloseStatus(userOrderDetail.getUiOrderCloseStatus() == 49 ? "1" : "2"); //
                                orderTicket.setUiOrderUid(userOrderDetail.getUiOrderUid() + "");
                                orderTicket.setDbTotalSwap(userOrderDetail.getDbTotalSwap() + "");
                                orderTicket.setDbOrderPrice(userOrderDetail.getDbOrderPrice() + "");

                                mDatas.add(orderTicket);
                            }
                            if (mOrderTickets.size() > 0) {
                                mOrderTickets.clear();
                            } else {
                                initValue();
                            }
                            // 筛选是持仓单的单据
                            for (OrderTicket orderTicket : mDatas) {
                                if ("2".equals(orderTicket.getOrderStatusValue()) && "1".equals(orderTicket.getUiOrderCloseStatus())) {
                                    mOrderTickets.add(orderTicket);
                                }
                            }
                            // 拿上一口价格
                            getHistoryData();
                        } else {
                            isFromFund = false;
                            showVisiable();
                            initValue();
                            return;
                        }
                    }else {
                        ErrorUtils.showToast(getActivity(), iErrorCode + "");
                    }
                }
                // 在这里如果没有行情的话，直接读缓存的
                getHistoryData();
            } catch (Exception e) {
                e.printStackTrace();
            }
            isFromFund = false;

        }

    }

    /**
     * 读历史数据
     */
    private void getHistoryData() {
        SaveQuotePush saveQuotePush = (SaveQuotePush) CacheManager.readObject(getActivity(), AppConfig.OFFETSHEET);
        // 得到报价表的缓存
        if (saveQuotePush != null) {
            List<BRealTimeData> getHistoryOFfersheets = saveQuotePush.mMyRelTimeDatas;
            if (saveQuotePush != null) {
                LogUtils.e("fundcache", "save" + getHistoryOFfersheets.size() + "");
            }
            setNetWorkRealTimeQuotePushes(getHistoryOFfersheets);
        }
    }

    private void showVisiable() {
        mLlFund.setVisibility(View.VISIBLE);
        DialogUtil.dimissDialog();
    }


    /**
     * 通过缓存数据计算并显示浮动的过程
     */
    public void setNetWorkRealTimeQuotePushes(List<BRealTimeData> getHistoryOFfersheets) {
        double newAccupidMoney = 0;
        double newFloatPrice = 0;
        // 接下来才是处理“浮动“数据的逻辑
        if (mOrderTickets.size() == 0) {
            initValue();
            return;
        }

        // 筛选
        // 综合成属于这个APP索要的数据

        // 遍历持仓单数据
        for (int i = 0; i <= mOrderTickets.size() - 1; i++) {
            OrderTicket orderTicket = mOrderTickets.get(i);

            // 遍历行情数据，是要把变化的商品的价格改了
            for (BRealTimeData timpush : getHistoryOFfersheets) {
                String ss_product_code = timpush.product_price_info.ss_product_code;
                // 如果是有浮动的数据item
                if (ss_product_code.equals(orderTicket.getSsProductCode())) {
                    orderTicket.uiPrice = timpush.ui_last_price + "";

                    // 遍历交易商品
                    for (ChooseGood chooseGood : mChooseGoods) {
                        if (chooseGood.goodsCode.equals(orderTicket.getSsProductCode())) {
                            orderTicket.sellPriceSpreed = chooseGood.sellPriceSpreed;
                            orderTicket.buyPriceSpreed = chooseGood.buyPriceSpreed;
                            orderTicket.contractUnit = chooseGood.contractUnit;
                            orderTicket.moneyHoldType = chooseGood.moneyHoldType;
                            orderTicket.initGuaranteeMoney = chooseGood.initGuaranteeMoney;
                        }
                    }

                    // calucatePerBill(orderTicket,newFloatPrice,newAccupidMoney,i);


                    // 计算当个单据的

                    //买方向单据浮动盈亏 =（（行情价+报价卖点差）- 持仓价格）* 合约单位 * 成交数量
                    // 行情价 --从行情数据中获取
                    // 报价卖点差，合约单位 ---从查询交易商品获取
                    // 持仓价格,成交数量  8052 持仓价格 (==开仓价格）14 成交数量(kai仓数量）  -- 从 单据数据（持仓单）中获取

                    // 每个单据
                    String orderTicket_$54 = orderTicket.getOrderDirectionValue();  // 方向
                    try {
                        double uiPrice = Double.parseDouble(orderTicket.uiPrice);  // 行情价
                        double sellPrice = Double.parseDouble(orderTicket.sellPriceSpreed);
                        double buyPrice = Double.parseDouble(orderTicket.buyPriceSpreed);
                        double holdPrice = Double.parseDouble(orderTicket.getDbHoldPrice());
                        double contractUnit = Double.parseDouble(orderTicket.contractUnit);
                        double commitUnit = Double.parseDouble(orderTicket.getDbExecuteSize());
                        // 判断买卖方向
                        double mFloatPrice = 0;
                        if (orderTicket_$54.equals("b")) {
                            mFloatPrice = ((uiPrice + sellPrice) - holdPrice) * contractUnit * commitUnit;
                        } else {
                            // 卖方向单据浮动盈亏 =（持仓价格 -（行情价+报价买点差））* 合约单位 * 成交数量
                            mFloatPrice = (holdPrice - (uiPrice + buyPrice)) * contractUnit * commitUnit;
                        }

                        newFloatPrice += mFloatPrice;   // 浮动盈亏累加

                        /**
                         * 计算占用保证金
                         */
                        Double initGuaranteeMoney = StringUtils.toDouble(orderTicket.initGuaranteeMoney); // 初始保障金
                        // 判断是保证金类型（包括比例与固定两种）
                        double mAccupidMoney = 0;
                        if (orderTicket.moneyHoldType.equals("1")) {  // 比例
                            // 占用保证金 = 商品信息->初始保证金 * 行情价 * 合约数量 * 单据数量
                            mAccupidMoney = initGuaranteeMoney * uiPrice * contractUnit * commitUnit;
                        } else if (orderTicket.moneyHoldType.equals("2")) {
                            // 占用保证金 = 商品信息->初始保证金 * 单据数量
                            mAccupidMoney = initGuaranteeMoney * commitUnit;
                        }
                        newAccupidMoney += mAccupidMoney;

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (i == mOrderTickets.size() - 1) {
                        if (calculate(newFloatPrice, newAccupidMoney)) return;
                    }
                }
            }
        }

    }

    /**
     * 初始化显示的值
     */
    private void initValue() {
        mTvFloatProfit.setText(0.00 + "");// 浮动盈亏
        mTvTakeMargin.setText(0.00 + "");       // 占用保证金
        mTvRiskRate.setText(0 + "%");  //     风险率
        mTvAvailableMargin.setText("0.00");
    }

    /**
     * 计算并显示浮动的过程
     *
     * @param bRealTimeQuotePushes
     */
    public void setRealTimeQuotePushes(List<BRealTimeQuotePush> bRealTimeQuotePushes) {
        this.mBrealTimeQuotePushes = bRealTimeQuotePushes;
        // 接下来才是处理“浮动“数据的逻辑
        double newFloatPrice = 0;
        double newAccupidMoney = 0;

        // 筛选
        // 综合成属于这个APP索要的数据

        // 遍历持仓单数据

        for (int i = 0; i <= mOrderTickets.size() - 1; i++) {
            OrderTicket orderTicket = mOrderTickets.get(i);


            // 每个单据
            String orderTicket_$54 = orderTicket.getOrderDirectionValue();  // 方向


            // 遍历行情数据，是要把变化的商品的价格改了
            for (BRealTimeQuotePush timpush : mBrealTimeQuotePushes) {
                String ss_product_code = timpush.product_price_info.ss_product_code;
                // 如果是有浮动的数据item
                if (ss_product_code.equals(orderTicket.getSsProductCode())) {
                    orderTicket.uiPrice = timpush.ui_price + "";
                }
            }

            // 遍历交易商品
            for (ChooseGood chooseGood : mChooseGoods) {
                if (chooseGood.goodsCode.equals(orderTicket.getSsProductCode())) {
                    orderTicket.sellPriceSpreed = chooseGood.sellPriceSpreed;
                    orderTicket.buyPriceSpreed = chooseGood.buyPriceSpreed;
                    orderTicket.contractUnit = chooseGood.contractUnit;
                    orderTicket.moneyHoldType = chooseGood.moneyHoldType;
                    orderTicket.initGuaranteeMoney = chooseGood.initGuaranteeMoney;
                }
            }

            // 计算当个单据的

            //买方向单据浮动盈亏 =（（行情价+报价卖点差）- 持仓价格）* 合约单位 * 成交数量
            // 行情价 --从行情数据中获取
            // 报价卖点差，合约单位 ---从查询交易商品获取
            // 持仓价格,成交数量  8052 持仓价格 (==开仓价格）14 成交数量(kai仓数量）  -- 从 单据数据（持仓单）中获取

            try {
                double uiPrice = Double.parseDouble(orderTicket.uiPrice);  // 行情价
                double sellPrice = Double.parseDouble(orderTicket.sellPriceSpreed);
                double buyPrice = Double.parseDouble(orderTicket.buyPriceSpreed);
                double holdPrice = Double.parseDouble(orderTicket.getDbHoldPrice());
                double contractUnit = Double.parseDouble(orderTicket.contractUnit);
                double commitUnit = Double.parseDouble(orderTicket.getDbExecuteSize());
                // 判断买卖方向
                double mFloatPrice = 0;
                if (orderTicket_$54.equals("b")) {
                    mFloatPrice = ((uiPrice + sellPrice) - holdPrice) * contractUnit * commitUnit;
                } else {
                    // 卖方向单据浮动盈亏 =（持仓价格 -（行情价+报价买点差））* 合约单位 * 成交数量
                    mFloatPrice = (holdPrice - (uiPrice + buyPrice)) * contractUnit * commitUnit;
                }

                newFloatPrice += mFloatPrice;   // 浮动盈亏累加

                /**
                 * 计算占用保证金
                 */
                Double initGuaranteeMoney = StringUtils.toDouble(orderTicket.initGuaranteeMoney); // 初始保障金
                // 判断是保证金类型（包括比例与固定两种）
                double mAccupidMoney = 0;
                if (orderTicket.moneyHoldType.equals("1")) {  // 比例
                    // 占用保证金 = 商品信息->初始保证金 * 行情价 * 合约数量 * 单据数量
                    mAccupidMoney = initGuaranteeMoney * uiPrice * contractUnit * commitUnit;
                } else if (orderTicket.moneyHoldType.equals("2")) {
                    // 占用保证金 = 商品信息->初始保证金 * 单据数量
                    mAccupidMoney = initGuaranteeMoney * commitUnit;
                }
                newAccupidMoney += mAccupidMoney;


                if (i == mOrderTickets.size() - 1) {
                    if (calculate(newFloatPrice, newAccupidMoney)) return;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 计算单个单据的过程
     *
     * @param orderTicket
     */
    public void calucatePerBill(OrderTicket orderTicket, double newFloatPrice, double newAccupidMoney, int i) {

        // 计算当个单据的

        //买方向单据浮动盈亏 =（（行情价+报价卖点差）- 持仓价格）* 合约单位 * 成交数量
        // 行情价 --从行情数据中获取
        // 报价卖点差，合约单位 ---从查询交易商品获取
        // 持仓价格,成交数量  8052 持仓价格 (==开仓价格）14 成交数量(kai仓数量）  -- 从 单据数据（持仓单）中获取

        // 每个单据
        String orderTicket_$54 = orderTicket.getOrderDirectionValue();  // 方向
        try {
            double uiPrice = Double.parseDouble(orderTicket.uiPrice);  // 行情价
            double sellPrice = Double.parseDouble(orderTicket.sellPriceSpreed);
            double buyPrice = Double.parseDouble(orderTicket.buyPriceSpreed);
            double holdPrice = Double.parseDouble(orderTicket.getDbHoldPrice());
            double contractUnit = Double.parseDouble(orderTicket.contractUnit);
            double commitUnit = Double.parseDouble(orderTicket.getDbExecuteSize());
            // 判断买卖方向
            double mFloatPrice = 0;
            if (orderTicket_$54.equals("b")) {
                mFloatPrice = ((uiPrice + sellPrice) - holdPrice) * contractUnit * commitUnit;
            } else {
                // 卖方向单据浮动盈亏 =（持仓价格 -（行情价+报价买点差））* 合约单位 * 成交数量
                mFloatPrice = (holdPrice - (uiPrice + buyPrice)) * contractUnit * commitUnit;
            }

            newFloatPrice += mFloatPrice;   // 浮动盈亏累加

            /**
             * 计算占用保证金
             */
            Double initGuaranteeMoney = StringUtils.toDouble(orderTicket.initGuaranteeMoney); // 初始保障金
            // 判断是保证金类型（包括比例与固定两种）
            double mAccupidMoney = 0;
            if (orderTicket.moneyHoldType.equals("1")) {  // 比例
                // 占用保证金 = 商品信息->初始保证金 * 行情价 * 合约数量 * 单据数量
                mAccupidMoney = initGuaranteeMoney * uiPrice * contractUnit * commitUnit;
            } else if (orderTicket.moneyHoldType.equals("2")) {
                // 占用保证金 = 商品信息->初始保证金 * 单据数量
                mAccupidMoney = initGuaranteeMoney * commitUnit;
            }
            newAccupidMoney += mAccupidMoney;

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (i == mOrderTickets.size() - 1) {
            if (calculate(newFloatPrice, newAccupidMoney)) return;
        }
    }

    /**
     * 要在这里计算，不然有问题
     *
     * @param newFloatPrice
     * @param newAccupidMoney
     * @return
     */
    private boolean calculate(double newFloatPrice, double newAccupidMoney) {
        // 浮动盈亏
        mTvFloatProfit.setText(StringUtils.double_df.format(newFloatPrice));
        if (newFloatPrice > 0) {
            mTvFloatProfit.setTextColor(getResources().getColor(R.color.red));
        } else {
            mTvFloatProfit.setTextColor(getResources().getColor(R.color.fund_float));
        }

        // 可用保证金
        //if (mTvAvailableMargin != null && mFund != null) {
        double mAvailMarginValue = mDbFreeMargin + newFloatPrice;
        mTvAvailableMargin.setText(StringUtils.double_df.format(mAvailMarginValue));
        //}

        mTvTakeMargin.setText(StringUtils.double_df.format(newAccupidMoney));       // 占用保证金
        /**
         * 计算净值     净值 = 可用保证金 + 占用保证金 + 冻结保证金
         */
        net_worth = mAvailMarginValue + newAccupidMoney + mFreezeMargin;
        mTvNetWorth.setText(StringUtils.double_df.format(net_worth));

        if (net_worth == 0) {
            return true;
        }
        /**
         * 风险率
         * a. Risk = 净值/占用
         Risk值越大，账户风险越小，越安全。
         */
        /*if (newAccupidMoney == 0) {
            return;
        }*/
        double riskRate = net_worth / newAccupidMoney * 100;
        mTvRiskRate.setText(StringUtils.df.format(riskRate) + "%");  //     风险率

        /**
         * 风险级别
         正常  >8121  追警   < 8122
         */
        if (mAdditionalMarginRisk < riskRate) {
            mTvRiskLevel.setText(R.string.risk_nomal);  //   风险级别
            mTvRiskLevel.setTextColor(getResources().getColor(R.color.fund_float));
            mTvRiskRate.setTextColor(getResources().getColor(R.color.fund_float));
        } else if (mAdditionalMarginRisk > riskRate && riskRate < mAutomaticRiskliquidation) {
            mTvRiskLevel.setText(R.string.risk_avoid);  //   风险级别
            mTvRiskLevel.setTextColor(getResources().getColor(R.color.red));
            mTvRiskRate.setTextColor(getResources().getColor(R.color.red));
        }
        return false;
    }
}
